#include "key.h"
#include "main.h"  // ??main.h???????
#include "oled.h"

#define KEY1 GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0)
#define KEY2 GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_10)

static uint8_t key1_pressed = 0;
static uint8_t key2_pressed = 0;

void KEY_Init(void) {
    GPIO_InitTypeDef GPIO_InitStructure;
    
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
    
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
    
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_Init(GPIOB, &GPIO_InitStructure);
}

void KEY_Scan(void) {
    static uint8_t key1_last = 1, key2_last = 1;
    uint8_t key1_current = KEY1;
    uint8_t key2_current = KEY2;
    
    if(!key1_last && key1_current) {
        key1_pressed = 1;
    }
    key1_last = key1_current;
    
    if(!key2_last && key2_current) {
        key2_pressed = 1;
    }
    key2_last = key2_current;
    
    if(key1_pressed) {
        key1_pressed = 0;
        if(currentMode == MODE_SELECTION) {
            menu_selection = !menu_selection;
            OLED_Clear();
            OLED_ShowString(0, 0, "Mode Select:", 16);
            OLED_ShowString(0, 2, menu_selection==0?">Bluetooth":" Bluetooth", 16);
            OLED_ShowString(0, 4, menu_selection==1?">Auto Mode":" Auto Mode", 16);
        } 
        else if(currentMode == AUTO_MODE_MENU) {
            currentSubMenu = (currentSubMenu + 1) % 3;
            OLED_Clear();
            OLED_ShowString(0, 0, "Auto Mode Menu", 16);
            OLED_ShowString(0, 2, currentSubMenu==TEMP_CTRL?">Temp Ctrl":" Temp Ctrl", 16);
            OLED_ShowString(0, 4, currentSubMenu==HUMIDITY_CTRL?">Humidity Ctrl":" Humidity Ctrl", 16);
            OLED_ShowString(0, 6, currentSubMenu==PIR_CTRL?">PIR Ctrl":" PIR Ctrl", 16);
        }
    }
    
    if(key2_pressed) {
        key2_pressed = 0;
        if(currentMode == MODE_SELECTION) {
            currentMode = menu_selection ? AUTO_MODE_MENU : BLUETOOTH_MODE;
            if(currentMode == AUTO_MODE_MENU) {
                OLED_Clear();
                OLED_ShowString(0, 0, "Auto Mode Menu", 16);
                OLED_ShowString(0, 2, ">Temp Ctrl", 16);
                OLED_ShowString(0, 4, " Humidity Ctrl", 16);
                OLED_ShowString(0, 6, " PIR Ctrl", 16);
            } else {
                OLED_Clear();
            }
        } 
        else if(currentMode == AUTO_MODE_MENU) {
            if(currentSubMenu == PIR_CTRL) {
                pirEnabled = !pirEnabled;
            }
            currentMode = AUTO_MODE_RUNNING;
            OLED_Clear();
        }
    }
}